package com.ndood.spider.hqgz.processor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.ndood.core.util.DateUtil;
import com.ndood.spider.hqgz.action.HqgzAction;
import com.ndood.spider.hqgz.dao.HjAttrDao;
import com.ndood.spider.hqgz.dao.HjGoodsDao;
import com.ndood.spider.hqgz.dao.HjGoodsPicDao;
import com.ndood.spider.hqgz.domain.HjAttr;
import com.ndood.spider.hqgz.domain.HjAttrQuery;
import com.ndood.spider.hqgz.domain.HjGoods;
import com.ndood.spider.hqgz.domain.HjGoodsPic;
import com.ndood.spider.hqgz.domain.HjGoodsQuery;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

/**
 * 方案一
 */
@Component
public class HqgzPageProcessor implements PageProcessor {
	Logger logger = LoggerFactory.getLogger(getClass());
	public static Integer CATEGORY = 8; //8 9 10 分类
	public static Integer SORT = 81; 
	
	@Autowired
	private HjAttrDao attrDao;
	
	@Autowired
	private HjGoodsDao goodsDao;
	
	@Autowired
	private HjGoodsPicDao goodsPicDao;

	@Override
	public Site getSite() {
		Site site = Site.me().setCharset("UTF-8").setCycleRetryTimes(3).setSleepTime(3 * 1000)
				.addHeader("Connection", "keep-alive").addHeader("Cache-Control", "max-age=0")
				.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0");
		return site;
	}

	@Override
	public void process(Page page) {
		if(page.getUrl()==null){
			return;
		}
		try {
			processDetailsPage(page);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void processDetailsPage(Page page) throws Exception {
		// Step1: 获取商品基本信息
		HjGoods goods = new HjGoods();
		goods.setStoreId(8);
		goods.setCatId(CATEGORY);
		goods.setStatus(1);
		goods.setAddtime(DateUtil.getPHPTimestamp());
		goods.setIsDelete(0);
		goods.setService("");
		goods.setSort(CATEGORY);
		goods.setUnit("件");
		goods.setIndividualShare(0);
		goods.setShareCommissionFirst(0d);
		goods.setShareCommissionSecond(0d);
		goods.setShareCommissionThird(0d);
		goods.setWeight(0d);
		goods.setFreight(0);
		goods.setFullCut("{\"pieces\":\"\",\"forehead\":\"\"}");
		goods.setIntegral("{\"give\":\"0\",\"forehead\":\"\",\"more\":\"\"}");
		goods.setShareType(0);
		
		// 获取商品详情页地址
		System.out.println("商品详情页地址："+page.getUrl());
		// 获取商品名称
		String name = page.getHtml().xpath("//*[@id='J_Title']/h3/text()").get();
		System.out.println("商品名称："+name);
		goods.setName(name);
		
		// 默认商品库存
		String originStock = page.getHtml().xpath("//*[@id='J_SpanStock']/text()").get();
		System.out.println("商品库存："+originStock);
		
		// 获取商品价格
		String price = page.getHtml().xpath("//*[@id='J_StrPrice']/em[2]/text()").get();
		System.out.println("原价："+price);
		goods.setOriginalPrice(Double.valueOf(price));
		
		String nowPrice = page.getHtml().xpath("//*[@id='J_PromoPriceNum']/text()").get();
		if(nowPrice==null) nowPrice = price;
		System.out.println("现价："+nowPrice);
		goods.setPrice(Double.valueOf(nowPrice));
		
		// 虚拟销量
		String sales = page.getHtml().xpath("//*[@id='J_SellCounter']/text()").get();
		System.out.println("虚拟销量：" + sales);
		goods.setVirtualSales(Integer.parseInt(sales));
		
		// 商品规格
		System.out.println(HqgzAction.tempSkuStr);
		// 获取商品图片
		List<Selectable> imageNodes = page.getHtml().xpath("//*[@id='J_UlThumb']/li").nodes();
		boolean isFirst = false;
		goods.setVideoUrl("");
		List<String> goodsPics = new ArrayList<String>();
		for (int i = 0; i < imageNodes.size(); i++) {
			Selectable imageNode = imageNodes.get(i);
			if(imageNode.xpath("//*[@id='J_VideoThumb']").get()!=null){
				String vedio_url = page.getHtml().xpath("//*[@id='detail']/div[1]/div[1]/div/div[1]/div[1]/div/div[2]/div/video/@src").get();
				System.out.println("视频地址："+vedio_url);
				goods.setVideoUrl("http:"+vedio_url);
				continue;
			}
			String goodsImgUrl = imageNode.xpath("//*/div/a/img/@data-src").get();
			if(isFirst==false){
				String coverPic = goodsImgUrl.replaceAll("_([0-9]+)x([a-z0-9]+).jpg", "_300x300.jpg");
				System.out.println("商品缩略图："+coverPic);
				goods.setCoverPic("http:"+coverPic);
				isFirst=true;
			}
			goodsImgUrl = goodsImgUrl.replaceAll("_([0-9]+)x([a-z0-9]+).jpg", "");
			System.out.println("商品图片"+i+"："+goodsImgUrl);
			goodsPics.add("http:"+goodsImgUrl);
		}
		// 获取商品描述信息 
		String desc = page.getHtml().xpath("//*[@id='description']").get();
		goods.setDetail(desc);
		
		// [{"attr_list":[{"attr_id":144,"attr_name":"原味包装（12片独立）"}],"num":20,"price":26,"no":"","pic":""},{"attr_list":[{"attr_id":145,"attr_name":"咸味蛋黄（双十二上新）"}],"num":9,"price":28,"no":"","pic":""}]
		// [{"attr_list":[{"attr_id":137,"attr_name":"默认"}],"num":368,"price":0,"no":"","pic":""}]
		List<Map<String,Object>> skus = new ArrayList<Map<String,Object>>();
		Gson gson = new Gson();
		if(HqgzAction.list.size()==0){
			goods.setUseAttr(0); 
			
			Map<String,Object> lmap = new HashMap<String,Object>();
			List<Map<String,Object>> attr_list = new ArrayList<Map<String,Object>>();
			// 设置属性名称和属性id列表
			Map<String,Object> a = new HashMap<String,Object>();
			a.put("attr_id", "137"); 
			a.put("attr_name", "默认"); 
			attr_list.add(a);
			lmap.put("attr_list", attr_list);
			// 设置属性库存
			lmap.put("num", Integer.valueOf(originStock));
			lmap.put("price", Double.valueOf(nowPrice));
			lmap.put("no", "");
			lmap.put("pic", "");
			skus.add(lmap);
			goods.setAttr(gson.toJson(skus));
		}else{
			goods.setUseAttr(1); 
			for (Map<String, String> map : HqgzAction.list) {
				Map<String,Object> lmap = new HashMap<String,Object>();
				List<Map<String,Object>> attr_list = new ArrayList<Map<String,Object>>();
				// 设置属性名称和属性id列表
				HjAttr attr = saveAttr(map.get("attrName"));
				Map<String,Object> a = new HashMap<String,Object>();
				a.put("attr_id", attr.getId()); 
				a.put("attr_name", attr.getAttrName()); 
				attr_list.add(a);
				lmap.put("attr_list", attr_list);
				
				// 设置属性库存
				lmap.put("num", Integer.valueOf(map.get("num")));
				lmap.put("price", Double.valueOf(map.get("price")));
				lmap.put("no", "");
				lmap.put("pic", "");
				skus.add(lmap);
			}
			goods.setAttr(gson.toJson(skus));
		}
		
		// Step2: 保存商品
		goods = saveGoods(goods);
	
		// Step3: 保存商品图片
		for (String picUrl : goodsPics) {
			saveGoodsPic(goods.getId(), picUrl);
		}
	}

	/**
	 * 根据商品id保存商品图片
	 */
	private void saveGoodsPic(int goodsId, String url) {
		HjGoodsPic po = new HjGoodsPic();
		po.setGoodsId(goodsId);
		po.setIsDelete(0);
		if(!url.contains("http")){
			url = "http:"+url;
		}
		po.setPicUrl(url);
		goodsPicDao.insert(po);
	}

	/**
	 * 根据商品名称获取商品信息如果存在则更新，如果不存在则新增
	 */
	private HjGoods saveGoods(HjGoods goodsPo) {
		HjGoodsQuery query = new HjGoodsQuery();
		query.createCriteria().andNameEqualTo(goodsPo.getName());
		List<HjGoods> list = goodsDao.selectByExample(query);
		if(list==null||list.size()==0){
			goodsDao.insert(goodsPo);
			return goodsPo;
		}
		return list.get(0);
	}

	/**
	 * 根据属性查询属性是否存在，如果不存在则新增并返回，如果存在则获取属性
	 */
	private HjAttr saveAttr(String attrName) {
		HjAttrQuery query = new HjAttrQuery();
		query.createCriteria().andAttrNameEqualTo(attrName);
		List<HjAttr> list = attrDao.selectByExample(query);
		if(list==null||list.size()==0){
			HjAttr po = new HjAttr();
			po.setAttrName(attrName);
			po.setAttrGroupId(14);
			po.setIsDefault((short)0);
			po.setIsDelete((short)0);
			attrDao.insert(po);
			return po;
		}
		return list.get(0);
	}

}